package com.tanhua.admin.listener;

import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: cl
 * @Date: 2022/5/18 - 05 - 18
 * @Description:
 */

/**
 * 动态审核消息监听器
 */
@Component
public class MovementListener {

    //动态服务
    @DubboReference
    private MovementApi movementApi;

    //阿里云绿色检测服务
    @Autowired
    private AliyunGreenTemplate aliyunGreenTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = "tanhua.audit.queue",//队列名字
                    durable = "true"),   //持久
            exchange = @Exchange(
                    value = "tanhua.audit.exchange",//交换机名称
                    type = ExchangeTypes.TOPIC),//交换机类型
            key = {"audit.movement"}   //监听器key
    ))
    public void listenCreate(String movementId) throws Exception {

        System.out.println("内容审核：id=" + movementId);

        try {
            //1、根据动态id查询动态
            Movement movement = movementApi.findByMovementId(movementId);

            //对于RocketMQ消息有可能出现重复，解决方法判断 (幂等性)
            Integer state = 0;
            if (movement != null && movement.getState() == 0) {
                //检测文本
                Map<String, String> textMap = aliyunGreenTemplate.greenTextScan(movement.getTextContent());

                //检测图片
                Map<String, String> imgMap = aliyunGreenTemplate.imageScan(movement.getMedias());

                if (textMap != null && imgMap != null) {
                    String textSuggestion = textMap.get("suggestion");
                    String imgSuggestion = imgMap.get("suggestion");
                    if ("block".equals(textSuggestion) || "block".equals(imgSuggestion)) {
                        //block表示未通过审核，状态标识为2
                        state = 2;
                    } else if ("pass".equals(textSuggestion) || "pass".equals(imgSuggestion)) {
                        //pass表示通过审核，状态标识为1
                        state = 1;
                    }
                }
            }
            movementApi.update(movementId, state);//更新动态表中的动态审核状态
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
